import numpy as np
import pandas as pd
from sklearn.utils import shuffle
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler

def test_draw(dataSet):
    plt.figure()
    X = dataSet[0:2000,0:1].tolist()
    Y = dataSet[0:2000,1:2].tolist()
    plt.scatter(X,Y)
    plt.show()

#绘图
def draw(dataSet,labels,titles):
    plt.figure()
    plt.suptitle(titles)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签\
    group = []
    X = []
    Y = []
    for data,i in zip(dataSet,labels):
        if i not in group:
            group.append(i)
            x_group = []
            x_group.append(data[0])
            y_group = []
            y_group.append(data[1])
            X.append(x_group)
            Y.append(y_group)
        else:
            X[group.index(i)].append(data[0])
            Y[group.index(i)].append(data[0])
    for x,y in zip(X,Y):
        plt.scatter(x,y)
    plt.legend(loc="upper right")  # 显示图中的标签
    plt.xlabel("数据编号")
    plt.ylabel('结果分类')
    plt.show()

#降维
def dimensionality_reduction(Data,n_components = 2):
    pca = PCA(n_components)
    return pca.fit_transform(Data)

#载入数据
def loadData(filename):
    Data = pd.read_csv(filename)
    Data.dropna(axis=0)
    shuffle(Data)
    Data.columns = ['A','B','C','D','E','F','G','H','I','J']
    row, columns = Data.shape
    myData = dimensionality_reduction(Data.iloc[:,0:9],2)
    minMax = MinMaxScaler()
    myData = minMax.fit_transform(myData)
    return row,columns,myData


#KMeans算法
def myKMeans(dataSet,n_clusters):
    kmeans = KMeans(n_clusters)  # n_clusters:number of cluster
    kmeans.fit(dataSet)
    print(kmeans.labels_)
    draw(dataSet,kmeans.labels_ ,titles="KMeans算法分类效果图")

if __name__ == '__main__':
    filename = 'shuttle.csv'
    row,columns,myData = loadData(filename)
    print(myData)
    test_draw(myData)
    myKMeans(myData,7)